<template>
  <view class="settings-container">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 顶部导航栏 -->
    <view class="top-nav">
      <view class="nav-left" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="nav-center">
        <text class="nav-title">店铺设置</text>
      </view>
    </view>

    <!-- 表单内容 -->
    <view class="form-content">
      <!-- 店铺Logo -->
      <view class="form-section">
        <text class="section-title">店铺Logo</text>
        
        <view class="logo-upload-section">
          <view class="logo-preview" @click="chooseLogo">
            <image
              v-if="formData.logo"
              :src="formData.logo"
              mode="aspectFill"
              class="logo-img"
              @error="onLogoError"
            />
            <view v-else class="logo-placeholder">
              <text class="placeholder-icon">🏪</text>
              <text class="placeholder-text">点击上传Logo</text>
            </view>
            <view v-if="uploadProgress > 0 && uploadProgress < 100" class="upload-mask">
              <text class="upload-text">{{ uploadProgress }}%</text>
            </view>
          </view>
          <view class="logo-tips">
            <text class="tip-text">• 建议尺寸：300×300 像素</text>
            <text class="tip-text">• 支持 jpg、png、gif，最大 5MB</text>
            <text class="tip-text">• 清晰的Logo能提升店铺品牌形象</text>
          </view>
        </view>
      </view>
      
      <!-- 基本信息 -->
      <view class="form-section">
        <text class="section-title">基本信息</text>
        
        <view class="form-item">
          <text class="item-label">店铺名称</text>
          <input 
            class="item-input" 
            v-model="formData.name" 
            placeholder="请输入店铺名称"
          />
        </view>

        <view class="form-item">
          <text class="item-label">店铺简介</text>
          <textarea 
            class="item-textarea" 
            v-model="formData.description" 
            placeholder="请输入店铺简介"
            maxlength="200"
          />
        </view>

        <view class="form-item">
          <text class="item-label">联系电话</text>
          <input 
            class="item-input" 
            v-model="formData.phone" 
            placeholder="请输入联系电话"
          />
        </view>

        <view class="form-item">
          <text class="item-label">店铺地址</text>
          <textarea 
            class="item-textarea" 
            v-model="formData.address" 
            placeholder="请输入店铺地址"
          />
        </view>

        <view class="form-item">
          <text class="item-label">营业时间</text>
          <input 
            class="item-input" 
            v-model="formData.businessHours" 
            placeholder="例如：10:00-22:00"
          />
        </view>
      </view>

      <!-- 配送设置 -->
      <view class="form-section">
        <text class="section-title">配送设置</text>
        
        <view class="form-item">
          <text class="item-label">起送价（元）</text>
          <input 
            class="item-input" 
            type="digit"
            v-model="formData.minOrderAmount" 
            placeholder="请输入起送价"
          />
        </view>

        <view class="form-item">
          <text class="item-label">配送费（元）</text>
          <input 
            class="item-input" 
            type="digit"
            v-model="formData.deliveryFee" 
            placeholder="请输入配送费"
          />
        </view>
      </view>

      <!-- 店铺状态 -->
      <view class="form-section">
        <text class="section-title">店铺状态</text>
        
        <view class="switch-item">
          <view class="switch-info">
            <text class="switch-label">店铺营业</text>
            <text class="switch-desc">关闭后用户将无法下单</text>
          </view>
          <switch 
            :checked="formData.status === 1" 
            @change="onStatusChange"
            color="#ff8a00"
          />
        </view>
      </view>

      <!-- 店铺数据 -->
      <view class="form-section">
        <text class="section-title">店铺数据</text>
        
        <view class="data-item">
          <text class="data-label">店铺评分</text>
          <text class="data-value">{{ formData.rating || '--' }}</text>
        </view>

        <view class="data-item">
          <text class="data-label">评价数量</text>
          <text class="data-value">{{ formData.ratingCount || 0 }}</text>
        </view>
      </view>

      <!-- 保存按钮 -->
      <view class="form-actions">
        <button class="save-btn" @click="saveSettings">保存修改</button>
      </view>
    </view>

    <!-- 底部导航 -->
    <view class="bottom-nav">
      <view class="nav-item" @click="goToHome">
        <text class="nav-icon">🏠</text>
        <text class="nav-label">首页</text>
      </view>
      <view class="nav-item" @click="goToOrders">
        <text class="nav-icon">📋</text>
        <text class="nav-label">订单</text>
      </view>
      <view class="nav-item" @click="goToFoods">
        <text class="nav-icon">🍱</text>
        <text class="nav-label">商品</text>
      </view>
      <view class="nav-item active">
        <text class="nav-icon">⚙️</text>
        <text class="nav-label">设置</text>
      </view>
    </view>
  </view>
</template>

<script>
import merchantService from '../../../services/merchant.js'
import authService from '../../../services/auth.js'

export default {
  data() {
    return {
      statusBarHeight: 0,
      uploadProgress: 0,
      formData: {
        logo: '',
        name: '',
        description: '',
        phone: '',
        address: '',
        businessHours: '',
        minOrderAmount: '',
        deliveryFee: '',
        status: 1,
        rating: 0,
        ratingCount: 0
      }
    }
  },
  onLoad() {
    this.getStatusBarHeight()
    this.loadMerchantInfo()
  },
  methods: {
    // 获取状态栏高度
    getStatusBarHeight() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 20
      document.documentElement.style.setProperty('--status-bar-height', this.statusBarHeight + 'px')
    },

    // 加载店铺信息
    async loadMerchantInfo() {
      try {
        const response = await merchantService.getMerchantInfo()
        const data = response.data || response
        
        console.log('店铺信息(原始):', data)
        console.log('原始数据的所有字段:', Object.keys(data))
        
        // 支持 camelCase 和 snake_case
        this.formData = {
          logo: data.logo || '',
          name: data.name || '',
          description: data.description || '',
          phone: data.phone || '',
          address: data.address || '',
          businessHours: data.businessHours || data.business_hours || '',
          minOrderAmount: String(data.minOrderAmount || data.min_order_amount || ''),
          deliveryFee: String(data.deliveryFee || data.delivery_fee || ''),
          status: data.status !== undefined ? data.status : 1,
          rating: data.rating || 0,
          ratingCount: data.ratingCount || data.rating_count || 0
        }
        
        console.log('店铺信息(处理后):', this.formData)
      } catch (error) {
        console.error('加载店铺信息失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      }
    },

    // 选择Logo
    chooseLogo() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0]
          
          // 检查文件大小
          uni.getFileInfo({
            filePath: tempFilePath,
            success: (fileInfo) => {
              if (fileInfo.size > 5 * 1024 * 1024) {
                uni.showToast({
                  title: '图片大小不能超过5MB',
                  icon: 'none'
                })
                return
              }
              this.uploadLogo(tempFilePath)
            },
            fail: () => {
              this.uploadLogo(tempFilePath)
            }
          })
        },
        fail: (error) => {
          console.error('选择图片失败:', error)
        }
      })
    },

    // 上传Logo
    uploadLogo(filePath) {
      const token = uni.getStorageSync('jwt_token')
      if (!token) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }

      this.uploadProgress = 0
      
      const uploadTask = uni.uploadFile({
        url: 'http://localhost:8080/api/v1/upload/image',
        filePath: filePath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (uploadRes) => {
          if (uploadRes.statusCode === 200) {
            try {
              const result = JSON.parse(uploadRes.data)
              if (result.code === 200 && result.data && result.data.url) {
                this.formData.logo = result.data.url
                this.uploadProgress = 100
                
                uni.showToast({
                  title: '上传成功',
                  icon: 'success'
                })
                
                setTimeout(() => {
                  this.uploadProgress = 0
                }, 1000)
              } else {
                throw new Error(result.message || '上传失败')
              }
            } catch (error) {
              console.error('解析响应失败:', error)
              uni.showToast({
                title: '上传失败：' + error.message,
                icon: 'none'
              })
              this.uploadProgress = 0
            }
          } else {
            uni.showToast({
              title: '上传失败：' + uploadRes.statusCode,
              icon: 'none'
            })
            this.uploadProgress = 0
          }
        },
        fail: (error) => {
          console.error('上传失败:', error)
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
          this.uploadProgress = 0
        }
      })
      
      uploadTask.onProgressUpdate((res) => {
        this.uploadProgress = res.progress
      })
    },

    // Logo加载失败
    onLogoError() {
      console.error('Logo加载失败:', this.formData.logo)
      uni.showToast({
        title: 'Logo加载失败',
        icon: 'none'
      })
    },

    // 店铺状态开关
    onStatusChange(e) {
      this.formData.status = e.detail.value ? 1 : 0
    },

    // 表单验证
    validateForm() {
      if (!this.formData.name.trim()) {
        uni.showToast({
          title: '请输入店铺名称',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.phone.trim()) {
        uni.showToast({
          title: '请输入联系电话',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.minOrderAmount || parseFloat(this.formData.minOrderAmount) < 0) {
        uni.showToast({
          title: '请输入正确的起送价',
          icon: 'none'
        })
        return false
      }

      if (!this.formData.deliveryFee || parseFloat(this.formData.deliveryFee) < 0) {
        uni.showToast({
          title: '请输入正确的配送费',
          icon: 'none'
        })
        return false
      }

      return true
    },

    // 保存设置
    async saveSettings() {
      if (!this.validateForm()) {
        return
      }

      try {
        uni.showLoading({ title: '保存中...' })

        // 准备提交数据
        const submitData = {
          logo: this.formData.logo || null,
          name: this.formData.name,
          description: this.formData.description,
          phone: this.formData.phone,
          address: this.formData.address,
          businessHours: this.formData.businessHours,
          minOrderAmount: parseFloat(this.formData.minOrderAmount),
          deliveryFee: parseFloat(this.formData.deliveryFee),
          status: this.formData.status
        }

        console.log('提交的数据:', submitData)
        
        await merchantService.updateMerchantInfo(submitData)

        uni.hideLoading()
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })

        // 重新加载数据
        setTimeout(() => {
          this.loadMerchantInfo()
        }, 500)

      } catch (error) {
        uni.hideLoading()
        console.error('保存失败:', error)
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      }
    },

    // 返回
    goBack() {
      uni.navigateBack()
    },

    // 导航
    goToHome() {
      uni.navigateTo({
        url: '/pages/merchant/home/home'
      })
    },

    goToOrders() {
      uni.navigateTo({
        url: '/pages/merchant/orders/orders'
      })
    },

    goToFoods() {
      uni.navigateTo({
        url: '/pages/merchant/foods/foods'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.settings-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 180rpx;
}

.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 999;
}

// 顶部导航栏
.top-nav {
  position: fixed;
  top: var(--status-bar-height);
  left: 0;
  right: 0;
  height: 88rpx;
  background: #fff;
  border-bottom: 1rpx solid #eee;
  display: flex;
  align-items: center;
  z-index: 998;
}

.nav-left {
  position: absolute;
  left: 0;
  width: 88rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  font-size: 36rpx;
  color: #333;
}

.nav-center {
  flex: 1;
  text-align: center;
}

.nav-title {
  font-size: 32rpx;
  font-weight: 700;
  color: #333;
}

// 表单内容
.form-content {
  margin-top: calc(var(--status-bar-height) + 88rpx + 20rpx);
  padding: 20rpx;
}

.form-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  display: block;
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
}

// Logo上传区域
.logo-upload-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24rpx;
}

.logo-preview {
  width: 200rpx;
  height: 200rpx;
  border-radius: 20rpx;
  overflow: hidden;
  position: relative;
  background: #f5f5f5;
  cursor: pointer;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.logo-img {
  width: 100%;
  height: 100%;
}

.logo-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #ffe0b2 0%, #ffcc80 100%);
  
  .placeholder-icon {
    font-size: 64rpx;
    margin-bottom: 12rpx;
  }
  
  .placeholder-text {
    font-size: 22rpx;
    color: #ff8a00;
    font-weight: 600;
  }
}

.upload-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  
  .upload-text {
    font-size: 32rpx;
    color: #fff;
    font-weight: 700;
  }
}

.logo-tips {
  width: 100%;
  padding: 20rpx;
  background: #fff9f0;
  border-radius: 12rpx;
  border: 1rpx solid #ffe0b2;
  
  .tip-text {
    display: block;
    font-size: 22rpx;
    color: #ff8a00;
    line-height: 1.8;
  }
}

// 表单项
.form-item {
  margin-bottom: 32rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.item-label {
  display: block;
  font-size: 26rpx;
  color: #333;
  margin-bottom: 16rpx;
}

.item-input {
  width: 100%;
  height: 72rpx;
  padding: 0 20rpx;
  border: 2rpx solid #e1e5e9;
  border-radius: 12rpx;
  font-size: 26rpx;
}

.item-textarea {
  width: 100%;
  min-height: 120rpx;
  padding: 20rpx;
  border: 2rpx solid #e1e5e9;
  border-radius: 12rpx;
  font-size: 26rpx;
  line-height: 1.6;
}

// 开关项
.switch-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 0;
}

.switch-info {
  flex: 1;
}

.switch-label {
  display: block;
  font-size: 26rpx;
  color: #333;
  margin-bottom: 8rpx;
}

.switch-desc {
  display: block;
  font-size: 22rpx;
  color: #999;
}

// 数据项
.data-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }
}

.data-label {
  font-size: 26rpx;
  color: #666;
}

.data-value {
  font-size: 28rpx;
  font-weight: 600;
  color: #ff8a00;
}

// 保存按钮
.form-actions {
  padding: 20rpx;
}

.save-btn {
  width: 100%;
  height: 88rpx;
  background: linear-gradient(135deg, #ff8a00 0%, #ffa726 100%);
  color: #fff;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 600;
}

// 底部导航
.bottom-nav {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 120rpx;
  background: #fff;
  border-top: 1rpx solid #eee;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding-bottom: env(safe-area-inset-bottom);
}

.nav-item {
  text-align: center;
  
  &.active {
    .nav-icon {
      font-size: 44rpx;
    }
    .nav-label {
      color: #ff8a00;
      font-weight: 600;
    }
  }
}

.nav-icon {
  display: block;
  font-size: 40rpx;
  margin-bottom: 6rpx;
}

.nav-label {
  display: block;
  font-size: 22rpx;
  color: #666;
}
</style>
